package com.soft.service;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.soft.entity.Team;
import com.soft.entity.TeamDefaultPermission;
import com.soft.entity.TeamMember;
import com.soft.mapper.TeamDefaultPermissionMapper;
import com.soft.mapper.TeamMapper;
import com.soft.mapper.TeamMemberMapper;

/**
 * 团队服务：团队/成员/权限 三个子域的业务规则与数据访问封装。
 */
@Service
public class TeamService {

    @Autowired
    private TeamMapper teamMapper;
    
    @Autowired
    private TeamMemberMapper teamMemberMapper;
    
    @Autowired
    private TeamDefaultPermissionMapper permissionMapper;

    // 团队基本操作
    public Team createTeam(String teamName, String description, Integer creatorId) {
    // 1) 组装团队实体并记录创建时间
        Team team = new Team();
        team.setTeamName(teamName);
        team.setDescription(description);
        team.setCreatorId(creatorId);
        team.setCreateTime(LocalDateTime.now());
        
    // 2) 入库，生成 teamId
        teamMapper.insert(team);

    // 3) 创建团队时自动添加创建者为 leader（活跃状态）
        TeamMember creator = new TeamMember();
        creator.setTeamId(team.getTeamId());
        creator.setUserId(creatorId);
        creator.setTeamRole("leader");
        creator.setStatus("active");
        creator.setJoinTime(LocalDateTime.now());
        teamMemberMapper.insert(creator);

        return team;
    }

    public boolean updateTeam(Integer teamId, String teamName, String description) {
    // 1) 读取并校验存在性
        Team team = teamMapper.selectById(teamId);
        if (team == null) {
            return false;
        }
        
    // 2) 覆盖基本信息（不做空值过滤，按现有接口约定处理）
        team.setTeamName(teamName);
        team.setDescription(description);
        return teamMapper.updateById(team) > 0;
    }

    public boolean deleteTeam(Integer teamId) {
    // 1) 校验存在性
        Team team = teamMapper.selectById(teamId);
        if (team == null) {
            return false;
        }
        
    // 2) 删除团队相关的所有数据（默认权限、成员），最后删除团队本身
        permissionMapper.deleteByTeamId(teamId);
        teamMemberMapper.deleteByTeamId(teamId);
        return teamMapper.deleteById(teamId) > 0;
    }

    public Team getTeam(Integer teamId) {
        return teamMapper.selectById(teamId);
    }

    public List<Team> getTeamsByCreator(Integer creatorId) {
        return teamMapper.selectByCreatorId(creatorId);
    }
    
    public List<Team> getTeamsByUserId(Integer userId) {
        return teamMapper.selectByUserId(userId);
    }
    
    public List<Team> getAllTeams() {
        return teamMapper.selectAll();
    }

    // 团队成员管理
    public boolean addMember(Integer teamId, Integer userId, String teamRole) {
    // 1) 检查用户是否已经是团队成员
        if (teamMemberMapper.selectByTeamAndUser(teamId, userId) != null) {
            return false;
        }

    // 2) 组装成员记录并入库
        TeamMember member = new TeamMember();
        member.setTeamId(teamId);
        member.setUserId(userId);
        member.setTeamRole(teamRole);
        member.setStatus("active");
        member.setJoinTime(LocalDateTime.now());
        
        return teamMemberMapper.insert(member) > 0;
    }

    /**
     * 移除成员：
     * - 自己退出：允许（leader 需确保不是最后一名）
     * - 操作他人：仅 leader 可移除，且禁止移除任何 leader
     */
    public boolean removeMember(Integer teamId, Integer userId, Integer operatorId) {
    // 1) 参数与存在性校验
        if (teamId == null || userId == null) {
            return false;
        }
        TeamMember target = teamMemberMapper.selectByTeamAndUser(teamId, userId);
        if (target == null || !"active".equals(target.getStatus())) {
            return false;
        }

    // 2) 自己退出：允许成员/管理员退出；若为 leader，仅当不是最后一名 leader 时允许
        if (operatorId != null && userId.equals(operatorId)) {
            if ("leader".equals(target.getTeamRole())) {
                int leaderCount = teamMemberMapper.countActiveLeaders(teamId);
                if (leaderCount <= 1) {
                    // 保护最后一名leader
                    return false;
                }
            }
            return teamMemberMapper.deleteMember(teamId, userId) > 0;
        }

    // 3) 操作他人：仅 leader 可移除，且禁止移除 leader 成员
        if (operatorId == null) {
            return false;
        }
        TeamMember operator = teamMemberMapper.selectByTeamAndUser(teamId, operatorId);
        if (operator == null || !"leader".equals(operator.getTeamRole())) {
            return false;
        }
        if ("leader".equals(target.getTeamRole())) {
            // 禁止移除任何leader（避免误操作）
            return false;
        }
        return teamMemberMapper.deleteMember(teamId, userId) > 0;
    }

    /** 更新成员角色：仅 leader 可操作，保护最后一名 leader 不被降级 */
    public boolean updateMemberRole(Integer teamId, Integer userId, String newRole, Integer operatorId) {
    // 1) 参数验证
        if (teamId == null || userId == null || newRole == null || newRole.trim().isEmpty() || operatorId == null) {
            System.out.println("updateMemberRole参数验证失败: teamId=" + teamId + ", userId=" + userId + ", newRole=" + newRole + ", operatorId=" + operatorId);
            return false;
        }
        
    // 2) 验证角色值是否有效
        if (!"leader".equals(newRole) && !"admin".equals(newRole) && !"member".equals(newRole)) {
            System.out.println("无效的角色值: " + newRole);
            return false;
        }
        
    // 3) 检查被修改的成员是否存在且为活跃状态
        int memberCount = teamMemberMapper.countActiveMembers(teamId, userId);
        if (memberCount == 0) {
            System.out.println("成员不存在或已被移除: teamId=" + teamId + ", userId=" + userId);
            return false;
        }

    // 4) 权限校验：只有 leader 可以修改成员角色（包括设为管理员）
        TeamMember operator = teamMemberMapper.selectByTeamAndUser(teamId, operatorId);
        if (operator == null || !"leader".equals(operator.getTeamRole())) {
            System.out.println("权限不足：操作者不是leader，operatorId=" + operatorId);
            return false;
        }

    // 5) 保护：不可将最后一名 leader 降级
        TeamMember target = teamMemberMapper.selectByTeamAndUser(teamId, userId);
        if (target != null && "leader".equals(target.getTeamRole()) && !"leader".equals(newRole)) {
            int leaderCount = teamMemberMapper.countActiveLeaders(teamId);
            if (leaderCount <= 1) {
                System.out.println("安全保护：不可将最后一名leader降级");
                return false;
            }
        }
        
    // 6) 执行更新并输出结果到控制台（可替换为日志）
    System.out.println("更新成员角色: teamId=" + teamId + ", userId=" + userId + ", newRole=" + newRole);
        int result = teamMemberMapper.updateRole(teamId, userId, newRole);
        System.out.println("更新结果: " + result);
        return result > 0;
    }

    public List<TeamMember> getTeamMembers(Integer teamId) {
        return teamMemberMapper.selectByTeamId(teamId);
    }

    public TeamMember getMember(Integer teamId, Integer userId) {
        return teamMemberMapper.selectByTeamAndUser(teamId, userId);
    }

    // 团队权限管理
    public boolean addPermission(Integer teamId, String resourceType, String action) {
    // 1) 组装默认权限并入库
        TeamDefaultPermission permission = new TeamDefaultPermission();
        permission.setTeamId(teamId);
        permission.setResourceType(resourceType);
        permission.setAction(action);
        
        return permissionMapper.insert(permission) > 0;
    }

    public boolean updatePermission(Integer permissionId, String resourceType, String action) {
    // 1) 读取并校验存在性
        TeamDefaultPermission permission = permissionMapper.selectById(permissionId);
        if (permission == null) {
            return false;
        }
        
    // 2) 覆盖字段后更新
        permission.setResourceType(resourceType);
        permission.setAction(action);
        return permissionMapper.updateById(permission) > 0;
    }

    public boolean deletePermission(Integer permissionId) {
        return permissionMapper.deleteById(permissionId) > 0;
    }

    public List<TeamDefaultPermission> getTeamPermissions(Integer teamId) {
    // 查询指定团队的默认权限列表
        return permissionMapper.selectByTeamId(teamId);
    }

    /** 简化的权限检查：leader 拥有所有权限，否则走团队默认权限 */
    public boolean checkPermission(Integer teamId, Integer userId, String resourceType, String action) {
    // 1) 检查用户是否是团队 leader
        TeamMember member = teamMemberMapper.selectByTeamAndUser(teamId, userId);
        if (member != null && "leader".equals(member.getTeamRole())) {
            return true;
        }
        
    // 2) 检查团队默认权限
        return permissionMapper.checkPermission(teamId, resourceType, action);
    }

    public boolean checkTeamNameExist(String teamName) {
    // 唯一性检查：用于创建团队时校验
        return teamMapper.findByTeamName(teamName) != null;
    }
}
